/**
 * TodoItem
 *
 */

import React, { FunctionComponent, CSSProperties, ChangeEvent } from 'react';
import { observer } from 'mobx-react';
import { List, Checkbox, Input } from 'antd';
import classnames from 'classnames';
import { TodoItemInstance } from '../../Stores/Todo/TodoItem';
import { TodoFormInstance } from '../../Stores/Todo/TodoForm';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import styles from './index.scss';

export interface TodoItemProps {
  style?: CSSProperties;
  todoItem: TodoItemInstance;
  editorForm: TodoFormInstance;
  deleteTodoItem: (id: string) => void;
  updateTodoItem: () => void;
}

const TodoItem: FunctionComponent<TodoItemProps> = ({ style, todoItem, editorForm, ...props }) => {

  const editing = editorForm.targetItemId === todoItem.id;

  const onSwitchChecked = (event: CheckboxChangeEvent) => todoItem.toggleComplete(event.target.checked);
  const onEditorTodoItem = () => editorForm.setTargetId(todoItem);;
  const onDeleteTodoItem = () => props.deleteTodoItem(todoItem.id);
  const onValueChange = (event: ChangeEvent<HTMLInputElement>) => editorForm.updateVal(event.target.value);

  return (
    <List.Item
      style={style}
      onDoubleClick={onEditorTodoItem}
      actions={
        editing
          ? undefined
          : [
              <a key="edit" onClick={onEditorTodoItem}>编辑</a>,
              <a key="delete" onClick={onDeleteTodoItem}>删除</a>
            ]
      }
    >
      <div className={styles.todoItem}>
        {editing ? (
          <Input
            value={editorForm.value}
            onChange={onValueChange}
            onPressEnter={props.updateTodoItem}
            onBlur={props.updateTodoItem}
          />
        ) : (
          <React.Fragment>
            <Checkbox checked={todoItem.isCompleted} onChange={onSwitchChecked} />
            <span className={classnames(styles.itemText, { [styles.completedItem]: todoItem.isCompleted })}>{todoItem.title}</span>
          </React.Fragment>
        )}
      </div>
    </List.Item>
  );
};

export default observer(TodoItem);
